<?php

namespace App\Support;

use App\Library\FeiShu\SendFs;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use Exception;
use Guanguans\Notify\Factory;

class OrganizationManageFsRobotSendSupport
{

    /**
     * 组织消息发送
     *
     * @param int $manageId 组织id
     * @param string $title 消息标题
     * @param string $msg 消息体
     * @throws Exception
     */
    public static function send(int $manageId, string $title, string $msg, string $robot = 'feishuRobot', array $cardArr = [])
    {
        if (HistoryOrderParam::$importOrderMode) {
            return;
        }

        try {
            $manageRobotConfig = ConfigService::config("openShop")[$robot];
            if ($manageRobotConfig) {
                collect($manageRobotConfig)->where("manageId", $manageId)->each(function ($v) use ($title, $msg, $cardArr) {
                    collect($v["robot"])->each(function ($robot) use ($title, $msg, $cardArr) {

                        if ($cardArr) {
                            $token = array_reverse(explode('/', $robot["hockUrl"]))[0] ?? '';
                            Factory::feiShu()
                                   ->setToken($token)
                                   ->setSecret($robot["secret"])
                                   ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($cardArr))
                                   ->send();
                        } else {
                            SendFs::newRobot()
                                  ->coverConfig($robot["hockUrl"], $robot["secret"])
                                  ->setTitleContent($title, $msg, "", false)
                                  ->send();
                        }

                    });
                });
            }
        } catch (Exception $e) {
            logException(
                "组织消息推送失败",
                $e,
                ["manageId" => $manageId, "title" => $title, "msg" => $msg],
                true,
                true
            );
        }
    }

}
